package com.example.demo.sys.util;

import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by mazeyi on 2019/12/6.
 */
public class ReflectionUtil {
    /**
     * 遍历对象所有属性输出,用作对象日志输出格式
     *
     * @return
     */
    public static String iteratorField(Object obj) {
        try {
            Class clz = obj.getClass();
            Field[] fields = clz.getDeclaredFields();
            StringBuffer sb = new StringBuffer();
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < fields.length; i++) {
                //得到属性
                Field field = fields[i];
                //打开私有访问
                field.setAccessible(true);
                //获取属性
                String name = field.getName();
                //获取属性值
                Object value = field.get(obj);
                map.put(name, value);
            }
            return JSONObject.toJSONString(map);
        } catch (IllegalAccessException e) {

        }
        return null;
    }
}